module RedisHashStore
  extend self

  def save(key_parts, number, value, field = nil)
    field ||= number
    redis.hset key(key_parts, number), field, value
  end

  def get(key_parts, number, field = nil)
    field ||= number
    redis.hget key(key_parts, number), field
  end

  def del(key_parts, number, field = nil)
    field ||= number
    if field.is_a?(Regexp)
      fields, cursor = [], 0
      loop do
        cursor, scan_fields = redis.hscan(key(key_parts, number), cursor.to_i)
        fields.concat scan_fields.map(&:first).grep(field)
        break if cursor.to_i == 0
      end
    else
      fields = [field]
    end
    unless fields.empty?
      redis.hdel key(key_parts, number), fields
    end
  end

  private

  def key(key_parts, number)
    [
      configuration.key_prefix,
      key_parts,
      number / configuration.fields_per_hash
    ].flatten.join(':')
  end
end
